package com.ktjy.actual.actual01;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LoggingInvocationHandler implements InvocationHandler {
    private final Object target;

    public LoggingInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //获取实现类中的方法详细
        Method methodTarget = target.getClass().getMethod(method.getName());
        //判断方法上是否有Log注解
        if (methodTarget.isAnnotationPresent(Log.class)) {
            String methodName = method.getName(); //获取方法名
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//创建时间格式
            LocalDateTime starToem = LocalDateTime.now(); //获取当前时间
//            starToem.format(formatter)   格式化时间
            System.out.println("[LOG]Method: " + methodName + " started at: " + starToem.format(formatter));

            Object result = method.invoke(target, args);
            LocalDateTime endTime = LocalDateTime.now(); //获取结束时间
            long duration =java.time.Duration.between(starToem, endTime).toMillis(); //计算时间差
            System.out.println("[LOG]Method: " + methodName + " ended at: " + endTime.format(formatter)); //输出结束时间
            System.out.println("[LOG]Method: " + methodName + " executed in: " + duration + " ms"); //输出执行时间
            return result;
        }
        return method.invoke(target, args);
    }
}
